package com.example.gateway.filter;

import com.example.gateway.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JwtAuthFilter extends AbstractGatewayFilterFactory<JwtAuthFilter.Config> {

    public JwtAuthFilter() {
        super(Config.class);
    }

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getPath().toString();

            // 检查白名单路径
            if (config.getWhitelistPaths() != null && config.getWhitelistPaths().contains(path)) {
                return chain.filter(exchange); // 白名单路径直接放行
            }

            // 获取 Token
            String token = request.getHeaders().getFirst("Authorization");
            if (token == null || !token.startsWith(config.getTokenPrefix())) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }

            token = token.substring(config.getTokenPrefix().length()); // 去掉前缀
            // 验证 Token
            if (!jwtUtil.validateToken(token)) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }

            // 将用户信息添加到请求头中
            String username = jwtUtil.getUsernameFromToken(token);
            ServerHttpRequest modifiedRequest = request.mutate()
                    .header("X-User-Name", username)
                    .build();

            return chain.filter(exchange.mutate().request(modifiedRequest).build());
        };
    }

    @Setter
    @Getter
    public static class Config {
        // 接收列表类型的白名单路径
        private List<String> whitelistPaths;
        // Token 前缀，例如：Bearer
        private String tokenPrefix;
    }
}